import decode from 'jwt-decode';
import {hashHistory} from 'react-router';
import {setLoginTo} from './data/app';

const TOKEN = 'token';
export const LOGIN = '/login';

export function getToken(forHeader) {
    const token = sessionStorage.getItem(TOKEN);
    if (token) {
        return forHeader ? `Bearer ${token}` : token;
    }
    return forHeader ? '' : token;
}

export function setToken(token) {
    sessionStorage.setItem(TOKEN, token);
}

export function removeToken() {
    sessionStorage.removeItem(TOKEN);
}

export function getUser() {
    const token = getToken();
    if (token) {
        return decode(token);
    }
}

export function login(history) {
    // 记录当前位置用于登录返回
    let returnTo = '/';
    let location = 'pathname';
    if (history === hashHistory) {
        location = 'hash';
    }
    location = window.location[location];
    if (location !== LOGIN) {
        returnTo = location;
    }
    setLoginTo(returnTo);
    if (!getToken()) {
        history.replace(LOGIN);
    }
}
